<template>
  <div>
    <div class="address-container">
      <!-- 添加地址 -->
      <div class="add-address">
        <el-form
          ref="addressRef"
          :model="addressForm"
          label-width="120px"
          :rules="rules"
        >
          <el-form-item label="所在地区" prop="region">
            <el-cascader
              v-model="addressForm.region"
              filterable
              :options="citys"
              :props="props"
              clearable
              @change="regionChange"
            />
          </el-form-item>
          <el-form-item label="详细地址" prop="detail">
            <div class="input-div">
              <el-input v-model="addressForm.detail" />
            </div>
          </el-form-item>
          <el-form-item label="收货人" prop="username">
            <div class="input-div">
              <el-input v-model="addressForm.username" />
            </div>
          </el-form-item>
          <el-form-item label="手机号" prop="phone">
            <div class="input-div">
              <el-input v-model="addressForm.phone" />
            </div>
          </el-form-item>
          <el-form-item>
            <el-checkbox v-model="addressForm.isDefault">设为默认</el-checkbox>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="onSubmit">立即创建</el-button>
            <el-button type="primary" @click="resetForm">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
      <!-- 地址列表 -->
      <div class="address-list">
        <el-table :data="userAddress" border style="width: 100%">
          <el-table-column prop="username" label="收货人" />
          <el-table-column label="所在地区" width="250">
            <template slot-scope="scope">
              <span>{{
                scope.row.province + scope.row.city + scope.row.town
              }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="detail" label="详细地址" width="250" />
          <el-table-column prop="phone" label="手机号" />
          <el-table-column label="默认地址">
            <template slot-scope="scope">
              <el-tag v-if="scope.row.isDefault" type="danger">是</el-tag>
              <el-tag v-else>否</el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="270">
            <template slot-scope="scope">
              <!-- <el-button
                size="mini"
                type="primary"
                @click="handleEdit(scope.$index, scope.row)"
                >编辑</el-button
              > -->
              <el-button
                size="mini"
                type="danger"
                @click="handleDelete(scope.$index, scope.row)"
              >删除</el-button>
              <el-button
                size="mini"
                type="success"
                @click="handleSetDefault(scope.$index, scope.row)"
              >设为默认</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>
  </div>
</template>
<script>
import { delAddress } from '@/api/address'

export default {

  data() {
    const validatePhone = (rule, value, callback) => {
      if (value) {
        const reg = /^1(3|4|5|6|7|8|9)\d{9}$/
        if (reg.test(value)) {
          callback()
        } else {
          callback(new Error('手机号格式不正确'))
        }
      } else {
        callback(new Error('请输入手机号'))
      }
    }

    const validateName = (rule, value, callback) => {
      if (value) {
        callback()
      } else {
        callback(new Error('请输入收货人'))
      }
    }

    const validateDetail = (rule, value, callback) => {
      if (value) {
        callback()
      } else {
        callback(new Error('请输入详细地址'))
      }
    }
    return {

      citys: require('@/common/city.json'),
      props: {
        value: 'name',
        label: 'name',
        children: 'area'
      },
      rules: {
        phone: [{ required: true, trigger: 'blur', validator: validatePhone }],
        username: [{ required: true, trigger: 'blur', validator: validateName }],
        detail: [{ required: true, trigger: 'blur', validator: validateDetail }],
        region: [{ required: true, message: '请选择地址', trigger: 'blur' }]
      },

      addressForm: {
        country: '中国',
        region: '',
        province: '',
        city: '',
        town: '',
        detail: '',
        username: '',
        phone: '',
        isDefault: false,
        fkUserId: ''
      }
    }
  },
  computed: {
    userDetail() {
      return this.$store.getters.userDetail
    },
    userAddress() {
      // console.log(this.$store.getters.userAddressList)

      return this.$store.getters.userAddressList
    }
  },
  created() {
    // this.checkUserAddress()
  },
  methods: {
    // 添加收货地址
    onSubmit() {
      this.$refs.addressRef.validate(valid => {
        if (valid) {
          if (this.addressForm.region.length === 1) {
            this.addressForm.province = this.addressForm.region[0]
          } else if (this.addressForm.region.length === 2) {
            this.addressForm.province = this.addressForm.region[0]
            this.addressForm.city = this.addressForm.region[1]
          } else if (this.addressForm.region.length === 3) {
            this.addressForm.province = this.addressForm.region[0]
            this.addressForm.city = this.addressForm.region[1]
            this.addressForm.town = this.addressForm.region[2]
          }
          this.addressForm.fkUserId = this.userDetail.id
          // console.log(this.addressForm)
          this.doAddAddress()
          // 提交表单
        } else {
          return false
        }
      })
    },

    resetForm() {
      this.$refs.addressRef.resetFields()
    },
    // 添加用户地址
    doAddAddress() {
      this.$store.dispatch('address/addAddress', this.addressForm).then(res => {
        this.$notify({
          title: '成功',
          message: '添加成功',
          type: 'success'
        })
        // 表单清除
        this.resetForm()
      }).catch(() => {
        this.$notify.error({
          title: '错误',
          message: '添加失败'
        })
      })
    },

    // 验证表单
    checkAddressForm() {

    },
    // 修改收获地址
    // handleEdit(index, obj) {

    // },
    // 删除收获地址
    handleDelete(index, obj) {
      if (this.userAddress[index].isDefault) {
        this.$notify.error({
          title: '错误',
          message: '删除失败,请先设置其他地址为默认地址'
        })
        return
      }
      delAddress(obj.id).then(res => {
        const arr = this.userAddress.filter(element => {
          return element.id !== obj.id
        })
        this.$store.commit('address/SET_USERADDRESSLIST', arr)
        this.$notify({
          title: '成功',
          message: '删除成功',
          type: 'success'
        })
      })
    },
    handleSetDefault(index, obj) {
      if (this.userAddress[index].isDefault) {
        this.$notify.error({
          title: '错误',
          message: '当前地址已是默认地址，无需设置'
        })
        return
      }
      this.$store.dispatch('address/setDefaultAdd', { uid: this.userDetail.id, aid: obj.id }).then(res => {
        this.$notify({
          title: '成功',
          message: '设置成功',
          type: 'success'
        })
      }).catch(() => {
        this.$notify.error({
          title: '错误',
          message: '操作失败'
        })
      })
    },
    regionChange(a, b, c) {
      // console.log(a, b, c)
    }

  }

}
</script>
<style lang="scss" scoped>
.input-div {
  width: 400px;
}
.address-list {
  margin-bottom: 40px;
}
</style>
